extends CharacterBody2D

@export var speed:float = 150 # 移动速度
@export var direction:Vector2 # 移动方向
@export var animatror:AnimatedSprite2D; # 动画节点
@export var isDead:bool = false # 游戏是否结束
@export var isHurt:bool = false # 是否受伤
@export var bullet_scene:PackedScene; # 外挂场景
@export var player_hp = 100;
func _ready() -> void:
	velocity = Vector2(50,0)

func _process(delta: float) -> void:
	if isDead or isHurt:
		$RunningSound.stop()
		return
	direction = Input.get_vector("Left","Right","Up","Down")
	velocity = direction * speed * delta * 100
	if velocity != Vector2.ZERO:
		animatror.flip_h = direction.x < 0
		animatror.play("running")
		if not $RunningSound.playing:
			$RunningSound.play()
	else:
		animatror.play('idle')
		$RunningSound.stop()
	
	move_and_slide()

func hurt():
		isHurt = true
		velocity = Vector2.ZERO
		if player_hp - 10 == 0:
			$"../GameStarted/PlayerHP".value = 0
			isDead = true
			$GameOverSound.play()
			animatror.play("die")
			get_tree().current_scene.show_game_over()
			$GameOverTimer.start()
		else:
			player_hp -= 10
			$"../GameStarted/PlayerHP".value = player_hp
			animatror.play("hurt")
			await get_tree().create_timer(0.5).timeout;
			isHurt = false
func on_fire():
	if not get_tree().current_scene.game_is_start:
		return
	# 移动/游戏结束：不允许射击
	if velocity != Vector2.ZERO or isDead or isHurt:
		return
	$FireSound.play();
	# 实例化子弹创建
	var bullet = bullet_scene.instantiate()
	# 偏移值
	var offset = Vector2(18,6)
	
	# 判断方向保持子弹和人物方向保持一致
	if animatror.flip_h:
		offset.x = offset.x*-1
		bullet.position = position+offset
		bullet.bullet_direction = -1
	else:
		bullet.position = position+offset		
		bullet.bullet_direction = 1
	get_tree().current_scene.add_child(bullet)


func on_timer_fire() -> void:
	# 定时开火
	on_fire()


func _on_game_over_timer_timeout() -> void:
	get_tree().reload_current_scene()
